import java.io.*;
enum FileEncrypt {
	UCS_2LE("UTF-16LE"),UCS_2BE("UTF-16BE"), UTF_8("UTF-8"),NO_BOM("US-ASCII");
	private String name;
	FileEncrypt(String name){
		this.name=name;
	}
	public String toString(){
		return name;
	}
}
final public class FileUtil{
	public static FileEncrypt checkType(String filename) 
	throws IOException{
		FileInputStream in=null;
		in=new java.io.FileInputStream(filename);
		int ch=0,b1=0,b2=0,b3=0,count=0;
		while((ch=in.read())!=-1){
			count++;
			if(count==1) b1=ch;
			if(count==2) b2=ch;
			if(count==3) b3=ch;
			if(count>3) break;
		}
		if(b1==255 && b2==254) return FileEncrypt.UCS_2LE;
		else if(b1==254 && b2==255) return FileEncrypt.UCS_2BE;
		else if(b1==239 && b2==187 && b3==191) return FileEncrypt.UTF_8;
		else return FileEncrypt.NO_BOM;	
	}
	public static StringBuffer readAll(String filename, 
	FileEncrypt encoding) throws IOException{
		BufferedReader inputStream = new BufferedReader(
			new InputStreamReader(
				new FileInputStream(filename),encoding.toString()
		));
		StringBuffer result=new StringBuffer();
		String l;
		while ((l = inputStream.readLine()) != null) {
			result.append(l+"\r\n");
		}
		inputStream.close();
		return result;
	}
	public static void write(String filename,StringBuffer content,
	FileEncrypt encoding) throws IOException{
		write(filename,content,encoding,true);
	}
	public static void write(String filename,StringBuffer content,
	FileEncrypt encoding,boolean useBOM) throws IOException{
		FileOutputStream fo=new FileOutputStream(filename);
		if(useBOM){
			if(encoding==FileEncrypt.UCS_2LE){
				fo.write(255);
				fo.write(254);
			}else if(encoding==FileEncrypt.UCS_2BE){
				fo.write(254);
				fo.write(255);
			}else if(encoding==FileEncrypt.UTF_8){
				fo.write(239);
				fo.write(187);
				fo.write(191);
			}
		}
		BufferedWriter out=new BufferedWriter(
			new OutputStreamWriter(fo,encoding.toString())
		);
		out.write(content.toString());
		out.close();
	}
	public static void main(String args[]) throws Exception{
		if(args.length>0){
			FileEncrypt type=FileUtil.checkType(args[0]);
			if(type==FileEncrypt.UTF_8 || type==FileEncrypt.NO_BOM)
				System.out.println(FileUtil.readAll(args[0],FileEncrypt.UTF_8));
			else
				System.err.println(type+" is not supported!");
		}
	}
}
